<template>
  <div>
    <q-card-section>
      <p class="text-grey-6">管理系统角色，根据角色分配不同权限。</p>
      <q-table
        :data="table.tableContentData"
        :columns="table.columns"
        :visibleColumns="table.visibleColumns"
        row-key="index"
        :loading="table.loading"
        :pagination.sync="table.initialPagination"
        rows-per-page-label="每页显示"
        flat
        bordered
        :separator="table.separator"
        selection="multiple"
        :selected.sync="table.selected"
      >
        <template v-slot:top>
          <q-space />
          <div class="col-4">
            <q-btn-group
              flat
              class="float-right"
            >
              <q-btn
                color="primary"
                icon="mdi-delete"
                label="批量删除"
                size="md"
                @click="getSelectedRows"
              />
              <q-btn
                color="primary"
                icon="mdi-table-row-plus-after"
                label="添加"
                size="md"
                @click="dialog.addRow = true"
              />
            </q-btn-group>
          </div>
        </template>
        <template v-slot:body-cell-Status="props">
          <q-td :props="props">
            <q-toggle
              v-model="props.row.Status"
              name="Status"
              disable
              v-show="props.row.Roles != 'all'"
            />
          </q-td>
        </template>
        <template v-slot:body-cell-Action="props">
          <q-td :props="props">
            <q-btn-group
              flat
              v-show="props.row.Roles != 'all'"
            >
              <q-btn
                icon="mdi-delete"
                label="删除"
                size="sm"
                @click="getDeleteRow(props.row)"
              />
              <q-btn
                icon="mdi-table-edit"
                label="编辑"
                size="sm"
                @click="getEditRow(props.row)"
              />
              <q-btn
                icon="mdi-call-split"
                label="权限"
                size="sm"
                @click="getRolesRow(props.row)"
              />
            </q-btn-group>
          </q-td>
        </template>
        <template v-slot:loading>
          <q-inner-loading
            showing
            color="primary"
          />
        </template>
      </q-table>
      <!-- 对话框-删除确认 -->
      <q-dialog v-model="dialog.delConfirm">
        <q-card>
          <q-card-section class="row items-center">
            <q-avatar
              icon="mdi-alert-circle-outline"
              text-color="primary"
            />
            <span class="q-ml-sm">确定要删除所选记录吗？</span>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              flat
              label="取消"
              color="primary"
              v-close-popup
            />
            <q-btn
              flat
              label="确定删除"
              color="primary"
              v-close-popup
              @click="deleteRows(deleteID)"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <!-- 对话框-编辑 -->
      <q-dialog
        v-model="dialog.editConfirm"
        persistent
        @input="clearRoles"
      >
        <q-card style="width:400px">
          <q-card-section>
            <div class="q-pb-md text-h6">编辑角色信息</div>
            <q-separator />
          </q-card-section>
          <q-card-section class="row items-center">
            <q-form
              class="q-gutter-y-md full-width"
              @submit.prevent.stop="editRow"
            >
              <q-input
                hide-bottom-space
                outlined
                v-model="roles.Name"
                label="请输入角色名称"
                name="Name"
                :rules="[val => !!val || '此项不能为空']"
              />
              <q-toggle
                v-model="roles.Status"
                label="启用状态"
                name="Status"
                left-label
              />
              <q-input
                outlined
                dense
                readonly
                v-model="roles.CreateUser"
                label="创建用户"
                name="CreateUser"
              />
              <q-input
                class="hidden"
                outlined
                dense
                readonly
                v-model="roles.Roles"
                label="角色权限"
                name="Roles"
              />
              <q-separator />
              <q-card-actions align="right">
                <q-btn
                  flat
                  label="取消"
                  color="primary"
                  v-close-popup
                />
                <q-btn
                  flat
                  label="修改"
                  color="primary"
                  v-close-popup
                  type="submit"
                />
              </q-card-actions>

            </q-form>
          </q-card-section>
        </q-card>
      </q-dialog>
      <!-- 对话框-添加 -->
      <q-dialog
        v-model="dialog.addRow"
        persistent
        @input="clearRoles"
      >
        <q-card style="width:400px">
          <q-card-section>
            <div class="q-pb-md text-h6">添加新角色</div>
            <q-separator />
          </q-card-section>
          <q-card-section class="row items-center">
            <q-form
              class="q-gutter-y-md full-width"
              @submit.prevent.stop="addRow"
            >
              <q-input
                hide-bottom-space
                outlined
                v-model="roles.Name"
                label="请输入角色名称"
                name="Name"
                :rules="[val => !!val || '此项不能为空']"
              />
              <q-toggle
                v-model="roles.Status"
                label="启用状态"
                name="Status"
                left-label
              />
              <q-input
                outlined
                dense
                readonly
                v-model="roles.CreateUser"
                label="创建用户"
                name="CreateUser"
              />
              <q-input
                class="hidden"
                outlined
                dense
                readonly
                v-model="roles.Roles"
                label="角色权限"
                name="Roles"
              />
              <q-separator />
              <q-card-actions align="right">
                <q-btn
                  flat
                  label="取消"
                  color="primary"
                  v-close-popup
                />
                <q-btn
                  flat
                  label="添加"
                  color="primary"
                  v-close-popup
                  type="submit"
                />
              </q-card-actions>

            </q-form>
          </q-card-section>
        </q-card>
      </q-dialog>
    </q-card-section>
    <!-- 右侧边栏 -->
    <q-drawer
      side="right"
      v-model="drawerRoles"
      overlay
      bordered
      content-class="bg-grey-1"
      id="q-drawer-roles"
    >
      <q-scroll-area class="fit">
        <div class="q-pa-md">
          <p class="text-primary text-h6">权限管理
            <q-btn
              outline
              round
              icon="mdi-arrow-right"
              size="xs"
              class="float-right"
              @click="drawerRoles = !drawerRoles"
            />
          </p>
          <p class="text-subtitle1 text-weight-bold blue-grey-9 ">角色 — {{roles.Name}}</p>
          <q-separator />
          <div class="q-pt-md">
            <q-tree
              class="col-12 col-sm-6"
              :nodes="rolesData"
              node-key="name"
              label-key="label"
              tick-strategy="leaf"
              :ticked.sync="roles.roles"
              default-expand-all
            />
            <q-separator spaced />
            <div class="row q-col-gutter-sm">
              <div class="col">
                <q-btn
                  unelevated
                  color="primary"
                  label="提交"
                  class="full-width"
                  @click="editRow()"
                />
              </div>
              <div class="col">
                <q-btn
                  label="关闭"
                  color="grey-4"
                  text-color="grey-8"
                  unelevated
                  class="full-width"
                  @click="drawerRoles = !drawerRoles"
                />
              </div>
            </div>

          </div>
        </div>
      </q-scroll-area>
    </q-drawer>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import routes from 'router/routes.js'

export default {
  name: 'PageRoles',
  components: {},
  props: {},
  data () {
    return {
      // 右侧边栏
      drawerRoles: false,
      // 树
      rolesData: [
        {
          label: '所有权限',
          name: 'all',
          children: routes
        }
      ],
      roles: {
        ID:'',
        Name: '',
        Status: true,
        CreateUser: this.$store.state.Author,
        roles: []
      },
      routes,
      selected: 'Pleasant surroundings',
      ticked: [ 'Quality ingredients', 'Good table presentation' ],
      expanded: [ 'Satisfied customers', 'Good service (disabled node)', 'Pleasant surroundings' ],

      // ---------- 表格
      table: {
        // 默认$Api参数
        defaultUpCategory: -1,
        defaultPageIndex: 1,
        // 初始化分页
        initialPagination: {
          sortBy: 'desc',
          descending: false,
          page: 1,
          rowsPerPage: 0,
          current: 1,
          rowsNumber: 0 //if getting data from a server
        },
        // 分割线模式可选值：horizontal (default)', 'vertical', 'cell', 'none'
        separator: 'horizontal',
        loading: true,
        // 可见列
        visibleColumns: ['Name', 'Status', 'CreateUser', 'Action'],
        columns: [
          {
            name: 'index',
            required: true,
            label: '序号',
            align: 'center',
            field: 'index'
          },
          { name: 'Name', align: 'left', label: '角色名称', field: 'Name' },
          { name: 'Status', align: 'center', label: '状态', field: 'Status' },
          { name: 'CreateUser', align: 'center', label: '创建用户', field: 'CreateUser' },
          { name: 'Action', align: 'center', label: '操作', field: '', style: 'width:300px' },
          { name: 'ID', align: 'left', label: 'ID', field: 'ID' },
          { name: 'Roles', align: 'left', label: '角色权限', field: 'Status' },
        ],
        tableContentData: [],
        selected: []
      },
      // ---------- 对话框
      dialog: {
        delConfirm: false,
        editConfirm: false,
        addRow: false,
      },
      deleteID: [],
      addRowResult: {},
      editRowResult: {}

    }
  },
  methods: {
    // 获取列表内容
    getList() {
      this.$api.RoleManageParams('', 'get').then (result => {
        this.table.tableContentData = result
        this.table.initialPagination.rowsNumber = result.length
        this.table.initialPagination.rowsPerPage = result.length
        // 生成序号
        this.table.tableContentData.forEach((row, index) => {
          row.index = index + 1
          if (row.Roles === null) {
            row.Roles = ''
          }
        })
        // 关闭加载动画
        this.table.loading = false
        // console.log(this.table.tableContentData)
        // console.log(result)
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 获得编辑的行数据
    getEditRow(value) {
      this.dialog.editConfirm = true
      // console.log(value)
      this.roles.ID = value.ID
      this.roles.Name = value.Name
      this.roles.Status = value.Status
      this.roles.CreateUser = value.CreateUser
      // 字符串转成数组，用来支持tree显示
      if (value.Roles === '') {
        this.roles.roles = []
      } else {
        this.roles.roles = value.Roles.split(',')
      }
      // console.log(this.roles)
    },
    // 获得编辑的权限数据
    getRolesRow(value) {
      this.drawerRoles = true
      // console.log(value)
      this.roles.ID = value.ID
      this.roles.Name = value.Name
      this.roles.Status = value.Status
      this.roles.CreateUser = value.CreateUser
      // 字符串转成数组，用来支持tree显示
      if (value.Roles === '') {
        this.roles.roles = []
      } else {
        this.roles.roles = value.Roles.split(',')
      }
      // console.log(this.roles)
    },
    // 提交权限编辑
    editRow() {
      const _editData = {
        Name: this.roles.Name,
        Status:this.roles.Status,
        CreateUser: this.roles.CreateUser,
      // 数组转成字符串，用来提交数据
        Roles: this.roles.roles.toString()
      }
      this.$api.RoleManageData(this.roles.ID, 'put', _editData).then (result => {
        if ( result === 'success') {
          this.drawerRoles = false
          this.clearRoles()
          //  重新请求数据列表
          this.getList()
          this.$utils.notify('数据修改成功！', 'positive')
        } else if ( result === 'error' ) {
          this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
        } else {
          this.$utils.notify(result, 'red-8')
        }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 添加新行
    addRow(evt) {
      this.addRowResult = this.$utils.formatFormData(evt)
      // console.log(this.addRowResult)
      this.$api.RoleManageData('', 'post', this.addRowResult).then (result => {
        if ( result === 'success') {
          this.clearRoles()
          //  重新请求数据列表
          this.getList()
        } else if ( result === 'error' ) {
          this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
        } else {
          this.$utils.notify(result, 'red-10')
        }
      }).catch (err => {
        switch (err.response.status) {
          case 401:
            this.unauthorized()
            break
        }
        console.log(err)
      })
    },
    // 获取多条选择行ID值数组
    getSelectedRows() {
      this.deleteID = []
      this.table.selected.map((row) => {
        this.deleteID.push( row.ID)
      })
      if (this.table.selected.length > 0) {
        this.dialog.delConfirm = true
      } else {
        this.$utils.notify('请选择要删除的记录','red-8')
      }
    },
    // 获取单条删除的row信息
    getDeleteRow(value) {
      this.deleteID = []
      this.deleteID.push(value.ID)
      this.dialog.delConfirm = true
    },
    // 提交服务器并删除本地信息
    deleteRows(rowid) {
      // 删除脚本
      const _ids =rowid
      this.$api.RoleManageData('', 'delete', _ids).then (result => {
        // console.log(result)
         if ( result === 'success') {
          //  重新请求数据列表
           this.getList()
         } else if ( result === 'error' ) {
           this.$utils.notify('数据库操作错误，请联系管理员', 'red-8')
         } else {
           this.$utils.notify(result, 'red-8')
         }
      }).catch (err => {
        console.log(err)
      })
      this.deleteID = []
      this.table.selected = []
    },
    // 清除权限内容
    clearRoles() {
        this.roles.Name = ''
        this.roles.ID = ''
        this.roles.CreateUser = ''
        this.roles.Status = true
        this.roles.roles = []
    },
    // session过期操作
    ...mapMutations(['changeLogin']),
    unauthorized() {
      // 弹出警告框
      this.$utils.notify('身份信息过期','red-8')
      // 清除vuex中的token
      this.changeLogin({ Authorization: '' })
      // 路由跳转
      this.$router.push('/Login', onComplete => {}, onAbort => {});
    }
  },
  mounted() {
    this.getList()
  },
}
</script>
<style scoped>
</style>
